﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="search-box">
        <div class="layui-form">
            <div class="layui-form-item" style="margin-bottom: 0;">
                <label class="layui-form-label">计划编码</label>
                <div class="layui-input-inline">
                    <input type="text" id="planCode" name="planCode" placeholder="请输入计划编码" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">计划名称</label>
                <div class="layui-input-inline">
                    <input type="text" id="planName" name="planName" placeholder="请输入计划名称" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">计划类型:</label>
                <div class="layui-input-inline">
                    <select id="planType" name="planType">
                        <option value="">请选择计划类型</option>
                        <option value="项目点检">项目点检</option>
                        <option value="项目保养">项目保养</option>
                    </select>
                </div>
                <label class="layui-form-label">状态:</label>
                <div class="layui-input-inline">
                    <select id="status" name="status">
                        <option value="">请选择状态</option>
                        <option value="草稿">草稿</option>
                        <option value="已确认">已确认</option>
                        <option value="审批中">审批中</option>
                        <option value="已审批">已审批</option>
                        <option value="已完成">已完成</option>
                        <option value="已拒绝">已拒绝</option>
                        <option value="已完成生成工单">已完成生成工单</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn" lay-submit lay-filter="searchForm">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary" onclick="resetForm()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button type="button" class="layui-btn layui-bg-blue" onclick="openAddMaintenanceView()"><i class="layui-icon layui-icon-addition"></i>新增</button>
                    <button type="button" class="layui-btn layui-bg-red" onclick="batchDeleteRecords()"><i class="layui-icon &#xe640; layui-icon-delete"></i>批量删除</button>
                </div>
            </div>
        </div>
    </div>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <table class="layui-table" lay-size="lg" id="maintenanceTable" lay-filter="maintenanceTable">
            <thead>
                <tr>
                    <th width="50">
                        <input type="checkbox" lay-filter="selectAll" title="全选">
                    </th>
                    <th>计划编码</th>
                    <th>计划名称</th>
                    <th>项目类型</th>
                    <th>开始日期</th>
                    <th>结束日期</th>
                    <th>频率</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    var form; // 声明全局form变量
    layui.use(['form'], function(){
        form = layui.form;  // 为全局form变量赋值
        
        // 初始化表格
        loadMaintenanceData();
        
        // 搜索表单提交
        form.on('submit(searchForm)', function(data){
            loadMaintenanceData();
            return false;
        });

        // 监听全选框
        form.on('checkbox(selectAll)', function(data){
            var checked = data.elem.checked;
            $('input[lay-filter="rowSelect"]').prop('checked', checked);
            form.render('checkbox');
        });

        // 监听行选择
        form.on('checkbox(rowSelect)', function(data){
            var allChecked = $('input[lay-filter="rowSelect"]').length === $('input[lay-filter="rowSelect"]:checked').length;
            $('input[lay-filter="selectAll"]').prop('checked', allChecked);
            form.render('checkbox');
        });
    });

    // 加载维护计划数据
    function loadMaintenanceData() {
        var queryData = {
            planCode: $("#planCode").val() ? $("#planCode").val() : "",
            planName: $("#planName").val() ? $("#planName").val() : "",
            planType: $("#planType").val() ? $("#planType").val() : "",
            status: $("#status").val() ? $("#status").val() : ""
        };

        $.ajax({
            url: '/Maintenance/GetMaintenance',
            type: 'GET',
            data: queryData,
            success: function(result) {
                if(result && result.length >= 0) {
                    // 如果是搜索操作，直接显示结果
                    if(queryData.planCode || queryData.planName || queryData.planType || queryData.status) {
                        renderTable(result);
                        return;
                    }

                    // 按计划编码排序
                    result.sort((a, b) => {
                        const codeA = (a.planCode || a.plancode || a.Plancode || '').toUpperCase();
                        const codeB = (b.planCode || b.plancode || b.Plancode || '').toUpperCase();
                        return codeA.localeCompare(codeB);
                    });

                    renderTable(result);
                } else {
                    layer.msg('暂无数据', {icon: 0});
                }
            },
            error: function(xhr) {
                console.log('错误详情:', xhr);
                layer.msg('获取数据失败，请检查网络连接', {icon: 2});
            }
        });
    }

    // 渲染表格数据
    function renderTable(data) {
        if(!Array.isArray(data)) {
            console.error('数据格式错误:', data);
            return;
        }
        
        var html = '';
        data.forEach(function(item) {
            html += '<tr>' +
                '<td><input type="checkbox" lay-filter="rowSelect" value="' + (item.id || '') + '" lay-skin="primary"></td>' +
                '<td>' + (item.planCode || item.plancode || item.Plancode || '') + '</td>' +
                '<td>' + (item.planName || item.PlanName || '') + '</td>' +
                '<td>' + (item.planType || item.PlanType || '') + '</td>' +
                '<td>' + formatDate(item.startDate || item.StartDate) + '</td>' +
                '<td>' + formatDate(item.endDate || item.EndDate) + '</td>' +
                '<td>' + (item.frequency || item.Frequency || '') + '</td>' +
                '<td>' + (item.status || item.Status || '') + '</td>' +
                '<td>' +
                '<a class="layui-btn layui-btn-xs" onclick="editMaintenance(\'' + (item.id || '') + '\')">编辑</a>' +
                '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteMaintenance(\'' + (item.id || '') + '\')">删除</a>' +
                '</td>' +
                '</tr>';
        });
        $("#tb").html(html);
        form.render('checkbox'); // 重新渲染复选框

        // 如果有更新的数据，高亮显示
        var updatedData = localStorage.getItem('updatedMaintenance');
        if(updatedData) {
            var updated = JSON.parse(updatedData);
            highlightEditedRow(updated.id);
        }
    }

    // 重置表单
    function resetForm() {
        $("#planCode").val('');
        $("#planName").val('');
        $("#planType").val('');
        $("#status").val('');
        loadMaintenanceData();
    }

    // 打开新增页面
    function openAddMaintenanceView() {
        window.location.href = '/Maintenance/AddMaintenanceView';
    }

    // 编辑维护计划
    function editMaintenance(id) {
        // 保存被编辑项的ID
        sessionStorage.setItem('editedMaintenanceId', id);
        window.location.href = '/Maintenance/UpdateMaintenanceView?id=' + id;
    }

    // 删除维护计划
    function deleteMaintenance(id) {
        layer.confirm('确定要删除这条记录吗？', {
            btn: ['确定', '取消']
        }, function() {
            // 这里可以添加删除接口的调用
            layer.msg('删除成功', {icon: 1});
        });
    }

    // 批量删除
    function batchDeleteRecords() {
        var selectedIds = [];
        $('input[lay-filter="rowSelect"]:checked').each(function(){
            selectedIds.push(parseInt($(this).val()));
        });

        if(selectedIds.length === 0) {
            layer.msg('请选择要删除的记录', {icon: 2});
            return;
        }

        layer.confirm('确定要删除选中的' + selectedIds.length + '条记录吗？', {
            btn: ['确定', '取消']
        }, function() {
            $.ajax({
                url: '/Maintenance/BatchDeleteMaintenance',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(selectedIds),
                headers: {
                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                success: function() {
                    layer.msg('批量删除成功', {icon: 1});
                    loadMaintenanceData(); // 重新加载数据
                },
                error: function(xhr) {
                    console.log('错误详情:', xhr);
                    layer.msg('删除失败，请检查网络连接', {icon: 2});
                }
            });
        });
    }

    // 日期格式化
    function formatDate(date) {
        if(!date) return '';
        var d = new Date(date);
        return d.getFullYear() + '-' + 
               padZero(d.getMonth() + 1) + '-' + 
               padZero(d.getDate());
    }

    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }

    // 高亮显示编辑过的行
    function highlightEditedRow(id) {
        var $row = $('#tb tr').filter(function() {
            return $(this).find('input[type="checkbox"]').val() === id;
        });
        
        if($row.length > 0) {
            // 滚动到编辑的行
            var container = $('.page-container');
            var rowTop = $row.position().top;
            var containerTop = container.scrollTop();
            var containerHeight = container.height();
            
            container.scrollTop(containerTop + rowTop - containerHeight/2);
            
            // 添加高亮效果
            $row.addClass('layui-bg-green');
            setTimeout(function() {
                $row.removeClass('layui-bg-green');
            }, 2000);
        }
    }

    // 添加样式
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = `
        .page-container {
            max-height: 600px;
            overflow-y: auto;
        }
        .layui-bg-green {
            transition: background-color 0.5s ease;
        }
    `;
    document.head.appendChild(style);

    // 在页面加载时检查并恢复数据顺序
    $(document).ready(function() {
        var savedTableData = sessionStorage.getItem('maintenanceTableData');
        if(savedTableData) {
            sessionStorage.removeItem('maintenanceTableData');
            loadMaintenanceData();
        } else {
            loadMaintenanceData();
        }
    });
</script>
